﻿using FineUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web.SessionState;
using Newtonsoft.Json.Linq;
using Think.Utils.Web;
using Think.Data;
using Think.Utils;
using Think.Extend;

namespace Think.Controls
{
    /// <summary>
    /// 列表页的数据绑定控件
    /// 实现分页和页面条数变更事件下的数据刷新
    /// </summary>
    public class ThinkGrid : FineUI.Grid, IRequiresSessionState
    {
        public object obj = new object();
        public ThinkGrid()
        {
            this.EmptyText = "<h2 style=\"margin:100px auto\">Oops...一条数据也没有找到！</h2>";
            this.PageSize = 20;
        }

        #region 初始化
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            DDLPageSize = this.FindControl("ddlGridPageSize") as ThinkDropDownList;
            if (DDLPageSize == null) return;
            if (!this.Page.IsPostBack)
            {
                DDLPageSize.AutoPostBack = true;
                DDLPageSize.Items.Insert(0, new FineUI.ListItem("10", "10"));
                DDLPageSize.Items.Insert(0, new FineUI.ListItem("20", "20"));
                DDLPageSize.Items.Insert(0, new FineUI.ListItem("50", "50"));
                DDLPageSize.Items.Insert(0, new FineUI.ListItem("100", "100"));
                DDLPageSize.Items.Insert(0, new FineUI.ListItem("200", "200"));
                DDLPageSize.SelectedValue = "20";
            }
            DDLPageSize.SelectedIndexChanged += new EventHandler(ddlGridPageSize_SelectedIndexChanged);
        }
        #endregion

        #region 属性
        [Category("属性")]
        [DefaultValue("ID DESC")]
        [Description("[AJAX属性]排序")]
        public string Orderby { get; set; }

        [Category("属性")]
        [DefaultValue("")]
        [Description("[AJAX属性]获取或设置统计字段")]
        public string SummaryField { get; set; }

        public object DataLogic
        {
            get
            {
                string url = RequestUtil.GetPageName();
                object o = Context.Session["GridDataLogic_" + url];
                return o;
            }
            set
            {
                string url = RequestUtil.GetPageName();
                Context.Session["GridDataLogic_" + url] = value;
            }
        }

        /// <summary>
        /// 获取列表数据SQL语句
        /// </summary>
        public string SQL
        {
            get
            {
                string url = RequestUtil.GetPageName();
                object o = Context.Session["SQL_" + url];
                return o == null ? string.Empty : o.ToString();
            }
            set
            {
                string url = RequestUtil.GetPageName();
                Context.Session["SQL_" + url] = value;
            }
        }

        /// <summary>
        /// 统计SQL
        /// </summary>
        public string SummarySQL
        {
            get
            {
                string url = RequestUtil.GetPageName();
                object o = Context.Session["SummarySQL_" + url];
                return o == null ? string.Empty : o.ToString();
            }
            set
            {
                string url = RequestUtil.GetPageName();
                Context.Session["SummarySQL_" + url] = value;
            }
        }


        /// <summary>
        /// 分页条数下拉框
        /// </summary>
        public ThinkDropDownList DDLPageSize
        {
            get
            {
                string url = RequestUtil.GetPageName();
                object o = Context.Session["DDLPageSize_" + url];
                return (o == null) ? null : (ThinkDropDownList)o;
            }
            set
            {
                string url = RequestUtil.GetPageName();
                Context.Session["DDLPageSize_" + url] = value;
            }
        }
        #endregion

        #region 加载数据

        /// <summary>
        /// 绑定数据
        /// </summary>
        /// <param name="sql"></param>
        public void LoadData(string sql)
        {
            if (string.IsNullOrWhiteSpace(sql))
            {
                return;
            }
            SQL = sql;
            var p = TRuntime.GetDB().Page<object>(this.PageIndex + 1, this.PageSize, sql);
            this.RecordCount = (int)p.TotalItems;
            this.DataSource = p.Items == null ? null : p.Items.ConvertToTable();
            this.DataBind();
        }

        /// <summary>
        /// 绑定统计数据,使用此方法必须设置EnableSummary=true,设置SummaryField属性(多个以,分隔)
        /// </summary>
        /// <param name="sql"></param>
        public void LoadSummary(string sql)
        {
            if (!this.EnableSummary)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(sql))
            {
                return;
            }
            SummarySQL = sql;
            //统计字段
            string fields = this.SummaryField;
            if (string.IsNullOrWhiteSpace(fields))
            {
                return;
            }
            string[] fieldarr = fields.Split(',');
            DataTable dtsummary = (DataTable)TRuntime.GetDB().Query<DataTable>(sql);
            if (dtsummary != null && dtsummary.Rows.Count > 0)
            {
                JObject summary = new JObject();
                for (int i = 0; i < fieldarr.Length; i++)
                {
                    float f = TypeTo.ObjectToFloat(dtsummary.Rows[0][fieldarr[i]].ToString(), 0);
                    summary.Add(fieldarr[i], f.ToString());
                }
                this.SummaryData = summary;
            }
        }

        #endregion

        #region 分页事件

        protected override void OnPageIndexChange(GridPageEventArgs e)
        {
            base.OnPageIndexChange(e);
            this.PageIndex = e.NewPageIndex;
            LoadData(SQL);
            LoadSummary(SummarySQL);
        }

        protected void ddlGridPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.PageSize = Convert.ToInt32(DDLPageSize.SelectedValue);
            this.PageIndex = 0;
            LoadData(SQL);
            LoadSummary(SummarySQL);
        }

        #endregion
    }
}
